package cn.edw.swu.bc.swucommunity

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.ContactsContract
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.util.ArrayList
import androidx.core.app.ActivityCompat
import androidx.core.content.ContentResolverCompat
import androidx.core.content.ContextCompat


/**
 * A simple [Fragment] subclass.
 * Use the [SessionFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class SessionFragment : Fragment() {
    // Session: Rename and change types of parameters

    val sessionData = arrayListOf<Session>()

    var toCallPhone: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            sessionData.add(Session("第一条测试消息", System.currentTimeMillis(), "毕成"))
            sessionData.add(Session("第二条测试消息", System.currentTimeMillis(), "林正英"))
            sessionData.add(Session("第三条测试消息", System.currentTimeMillis(), "郭恒系"))
            sessionData.add(Session("第四条测试消息", System.currentTimeMillis(), "刘德华"))
            sessionData.add(Session("第五条测试消息", System.currentTimeMillis(), "伍胜"))

            adapter = SessionAdapter()

        }
    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_session, container, false)
        val recyclerView = view.findViewById<RecyclerView>(R.id.session_recycler_view)

        Log.d("@@create", "创建sessionFragement")
        recyclerView.layoutManager = LinearLayoutManager(view.context)
        adapter = SessionAdapter()
        recyclerView.adapter = adapter
        toReadContacts()
        return view
    }

    private fun toReadContacts() {
        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_CONTACTS)
            == PackageManager.PERMISSION_GRANTED
        ) {
            readContacts(requireActivity())
        } else {
            ActivityCompat.requestPermissions(
                requireActivity(),
                arrayOf(Manifest.permission.READ_CONTACTS),
                REQ_CODE_CONTACT
            )
        }
    }

    fun toCall(phone: String) {
        if (ContextCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.CALL_PHONE
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            doCall(phone, requireActivity())
        } else {
//            requestPermissions()
            toCallPhone = phone
            ActivityCompat.requestPermissions(
                requireActivity(),
                arrayOf(Manifest.permission.CALL_PHONE),
                REQ_CODE
            )
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    }

    companion object {
        lateinit var adapter: SessionAdapter
        val REQ_CODE = 1024
        val REQ_CODE_CONTACT = 1025


        @JvmStatic
        fun newInstance() =
            SessionFragment().apply {
                arguments = Bundle().apply {
                }
            }

        @JvmStatic
        fun readContacts(activity: Activity) {
            val cursor = ContentResolverCompat.query(
                activity.contentResolver,
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null,
                null,
                null,
                null,
                null
            )

            val arr = arrayListOf<Session>()
            while (cursor.moveToNext()) {
                val nameIdx =
                    cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
                val phoneIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                if (nameIdx >= 0) {
                    val name = cursor.getString(nameIdx)
                    val phone = cursor.getString(phoneIdx)
                    arr.add(Session(phone, System.currentTimeMillis(), name))
                }
            }
            adapter.setData(arr)
        }

        @JvmStatic
        fun doCall(phone: String, activity: Activity) {
            val intent = Intent(Intent.ACTION_CALL)
            intent.data = Uri.parse("tel:$phone")
            activity.startActivity(intent)
        }
    }

    inner class SessionAdapter : RecyclerView.Adapter<SessionViewHolder>() {
        val data = arrayListOf<Session>()

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SessionViewHolder {
            val view =
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.session_item, parent, false)
            return SessionViewHolder(view).apply {
                senderPic = view.findViewById(R.id.sender_pic)
                messageContent = view.findViewById(R.id.message_content)
                sendTime = view.findViewById(R.id.send_time)
                senderName = view.findViewById(R.id.sender_name)
            }
        }

        override fun onBindViewHolder(holder: SessionViewHolder, position: Int) {
            holder.render(data[position])
        }

        override fun getItemCount(): Int {
            return data.size
        }

        fun setData(arr: ArrayList<Session>) {
            data.clear()
            data.addAll(arr)
            notifyDataSetChanged()
        }

    }

    inner class SessionViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        var senderPic: ImageView? = null
        var messageContent: TextView? = null
        var senderName: TextView? = null
        var sendTime: TextView? = null


        fun render(session: Session) {
            senderName?.text = session.senderName
            sendTime?.text = session.sendTime.toString()
            messageContent?.text = session.lastMessage
            Log.d("@@sess",messageContent?.text.toString())
            senderPic!!.setOnClickListener() {
                toCall(messageContent?.text.toString())
                Log.d("@@sess",messageContent?.text.toString())
            }
//            senderPic?.background=session.senderPic
        }
    }

}